<template>
    <div>
         <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="120px">
             <el-form-item label="服务类型：" prop="type">
                <el-select v-model="queryParams.type" placeholder="服务类型" size="small">
                    <el-option v-for="item in paramsTypeArr" :label="item.label" :key="item.value" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="服务名：" prop="service">
                <el-input v-model="queryParams.service" placeholder="服务名" size="small"></el-input>
            </el-form-item>
             <el-form-item label="方法名：" prop="method">
                <el-input v-model="queryParams.method" placeholder="方法名" size="small"></el-input>
            </el-form-item>
             <el-form-item label="接口名称：" prop="name">
                <el-input v-model="queryParams.description" placeholder="接口名称" size="small"></el-input>
            </el-form-item>
             <el-form-item label="版本：" prop="version">
                <el-input v-model="queryParams.version" placeholder="版本" size="small"></el-input>
            </el-form-item>
             <el-form-item label="分组：" prop="group">
                <el-input v-model="queryParams.group" placeholder="分组" size="small"></el-input>
            </el-form-item>
             <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
         </el-form>
         <el-row :gutter="10">
                <el-col :span="24">
                    <div style="margin-bottom: 10px;padding: 0 10px">
                        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                        <el-button type="success" plain icon="el-icon-upload2" size="small" @click="handleAdd">导入</el-button>
                        <el-button type="primary" plain icon="el-icon-download" size="small" @click="handleExport">导出</el-button>
                    </div>
                </el-col>
             </el-row>
         <el-table :data="tableData" size="mini" ref="tableRef" border style="width: 100%">
             <el-table-column type="selection" width="55"></el-table-column>
             <el-table-column type="index" label="#" width="55"></el-table-column>
             <el-table-column prop="type" label="服务类型">
                <template slot-scope="{row}">
                    <span v-if="row.type===1">Dubbo</span>
                    <span v-if="row.type===2">gRPC</span>
                    <span v-if="row.type===3">HTTP</span>
                </template>
             </el-table-column>
             <el-table-column prop="service" label="服务名"></el-table-column>
             <el-table-column prop="method" label="方法名"></el-table-column>
             <el-table-column prop="name" label="接口名称"></el-table-column>
             <el-table-column prop="version" label="版本"></el-table-column>
             <el-table-column prop="group" label="分组"></el-table-column>
             <el-table-column prop="paramTypes" label="参数类型"></el-table-column>
             <el-table-column prop="note" label="备注"></el-table-column>
            <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
      </el-table>
       <el-pagination
                v-show="total>0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
                :current-page="1"
                :page-sizes="[10, 20, 30, 40,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination-container"
                :total="total">
        </el-pagination>
        <el-dialog :title="title" :visible.sync="addFormVisible">
             <el-form :model="addForm" :rules="rules" ref="addForm" :disabled="mode==='view'">
                <el-form-item  prop="rpcServiceId" label="服务信息：" required :label-width="formLabelWidth">
                    <el-row :gutter="20">
                        <el-col :span="20">
                            <el-select v-model="addForm.rpcServiceId" placeholder="服务类型" size="small" style="width: 100%">
                                <el-option v-for="item in serviceList" :label="item.service" :key="item.id" :value="item.id">
                                    <span style="float: left">{{ item.service }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.version }}-{{item.service}} 
                                        {{item.type===1?'Dubbo':item.type===2?'gRpc':'HTTP'}}
                                    </span>
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="2" v-if="mode!=='view'">
                            <el-button type="text" @click="addServiceClick">新增服务</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item  prop="name" label="接口名称：" required :label-width="formLabelWidth">
                    <el-input type="textarea" rows="4" v-model="addForm.name" autocomplete="off" size="mini" placeholder="请输入接口名称"></el-input>
                    <div class="tips">接口名称是一个自定义名称，如：获取用户信息接口</div>
                </el-form-item>
                <el-form-item  prop="method" label="方法名：" required :label-width="formLabelWidth">
                    <el-input v-model="addForm.method" autocomplete="off" size="mini" placeholder="请输入权限编号"></el-input>
                    <div  class="tips">方法名，如：getUserInfo</div>
                </el-form-item>
                <el-form-item  prop="note" label="备注：" :label-width="formLabelWidth">
                    <el-input v-model="addForm.note" autocomplete="off" size="mini" placeholder="请输入权限编号"></el-input>
                </el-form-item>
             </el-form>
            <div slot="footer" class="dialog-footer" v-if="mode!=='view'">
                <el-button type="primary" @click="handleSubmit('addForm')" size="small">保存</el-button>
                <el-button @click="addFormVisible = false" size="small">取消</el-button>
            </div>
         </el-dialog>
         <el-dialog title="新增Rpc服务" :visible.sync="serviceFormVisible">
             <el-form :model="rpcForm" :rules="rules" ref="rpcForm">
                    <el-form-item  prop="type" label="服务类型：" required :label-width="formLabelWidth">
                        <el-radio-group v-model="rpcForm.type">
                            <el-radio v-for="item in typeArr" :label="item.value" :key="item.value">{{item.label}}</el-radio>
                        </el-radio-group>
                        <div class="tips" v-if="rpcForm.type===3">只需填写不支持服务发现的HTTP服务</div>
                    </el-form-item>
                      <el-form-item  prop="service" label="服务名：" required :label-width="formLabelWidth">
                          <el-input v-model="rpcForm.service" autocomplete="off" size="mini" placeholder="请输入权限编号"></el-input>
                          <div class="tips" v-if="rpcForm.type===1">服务名须包含包路径，如：com.abc.UserService; 保存后服务名不能修改</div>
                          <div class="tips" v-if="rpcForm.type===2">服务名须包含包路径，如：com.abc.UserService，gRPC服务需启用反射功能(样例) ; 保存后服务名不能修改</div>
                          <div class="tips" v-if="rpcForm.type===3">服务名可自定义, 网关会根据该名称来获取实例的IP和端口，如：OrderService; 保存后服务名不能修改</div>
                      </el-form-item>
                      <el-form-item  prop="description" label="描述：" required :label-width="formLabelWidth">
                            <el-input type="textarea" rows="3" v-model="rpcForm.description" autocomplete="off" size="mini" placeholder="请输入描述"></el-input>
                      </el-form-item>
                      <el-form-item  prop="version" label="版本：" required :label-width="formLabelWidth" v-if="rpcForm.type===1">
                            <el-input v-model="rpcForm.version" autocomplete="off" size="mini" placeholder="请输入权限编号"></el-input>
                            <div class="tips">Dubbo接口的版本号</div>
                      </el-form-item>
                        <el-form-item  prop="instance" label="实例列表：" required :label-width="formLabelWidth" v-if="rpcForm.type!==1">
                            <el-input type="textarea" rows="3" v-model="rpcForm.instance" autocomplete="off" size="mini" placeholder="如：10.2.3.114:8080或user.fizzgate.com:9090"></el-input>
                            <div class="tips">输入HTTP服务的实例IP:Port 或 域名:Port, 多个实例用逗号分隔</div>
                      </el-form-item>
                      <el-form-item  prop="group" label="分组：" required :label-width="formLabelWidth">
                            <el-input v-model="rpcForm.group" autocomplete="off" size="mini" placeholder="请输入权限编号"></el-input>
                            <div class="tips">Dubbo接口的分组</div>
                     </el-form-item>
                     <el-form-item  prop="loadBalanceType" label="负载均衡：" :label-width="formLabelWidth" required v-if="rpcForm.type!==1">
                        <el-radio-group v-model="rpcForm.loadBalanceType">
                            <el-radio v-for="item in loadBalanceArr" :label="item.value" :key="item.value">{{item.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                 </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleRpcSave('rpcForm')" size="small">保存</el-button>
                <el-button @click="serviceFormVisible = false" size="small">取消</el-button>
            </div>
         </el-dialog>
    </div>
</template>

<script>
import { getRpcInterfaceList,saveRpc,getRpcServiceList,saveService,download,remove } from '@/api/rpc/interface.api.js'
    export default {
        data() {
            return {
                paramsTypeArr: [
                    {label: 'Dubbo',value: 1},
                    {label: 'gRPC',value: 2},
                ],
                typeArr: [
                    {label: 'Dubbo',value: 1},
                    {label: 'gRPC',value: 2},
                    {label: 'HTTP',value: 3},
                ],
                serviceList: [],
                queryParams: {
                    current: 1,
                    size: 10
                },
                tableData: [],
                addForm: {},
                addFormVisible: false,
                serviceFormVisible: false,
                formLabelWidth: '120px',
                title: '新增',
                rules: {},
                total:0,
                rpcForm: {
                    type: 1,
                    loadBalanceType: 1
                },
                typeArr: [
                    {label: 'Dubbo',value: 1},
                    {label: 'gRPC',value: 2},
                    {label: 'HTTP',value: 3},
                ],
                 loadBalanceArr: [
                    {label: '轮循',value: 1},
                    {label: '随机',value: 2},
                ],
                mode:'add'
            }
        },
        async mounted() {
            this.getList();
            const params = {
                typesForCondition: '1,2',
                current: 1,
                size: -1
            }
            const result = await getRpcServiceList(params);
            if(result.code===200) {
                this.serviceList = result.data.records
            }
        },
        methods: {
            getList() {
                getRpcInterfaceList(this.queryParams).then(res=>{
                    if(res.code === 200) {
                        this.tableData = res.data.records;
                        this.total = res.data.total;
                    }
                })
            },
            // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
           },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
            handleAdd() {
                this.addFormVisible = true;
                this.mode = 'add';
            },
            addServiceClick() {
                this.serviceFormVisible = true;
            },
            handleSubmit(formName) {
                 this.$refs[formName].validate(async(valid) => {
                    if (valid) {
                        const result = await saveService(this.addForm);
                        if(result.code === 200) {
                            this.$message.success('保存成功');
                            this.addFormVisible = false;
                            this.getList();
                        }
                    } else {
                        return false;
                    }
                });
            },
            handleRpcSave(formName) {
                 this.$refs[formName].validate(async(valid) => {
                    if (valid) {
                        const result = await saveRpc(this.rpcForm);
                        if(result.code === 200) {
                            this.$message.success('保存成功');
                            this.serviceFormVisible = false;
                        }
                    } else {
                        console.log('error submit!!');
                       
                        return false;
                    }
                });
            },
            handleEdit(row){
                 this.addForm = JSON.parse(JSON.stringify(row));
                this.addFormVisible = true;
                this.mode = 'edit';
            },
            handleView(row){
                this.addForm = row;
                this.addFormVisible = true;
                this.mode = 'view';
            },
             handleDelete(id) {
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        const result = await remove(id);
                        if(result.code === 200) {
                             this.$message({
                                type: 'success',
                                message: '删除成功!'
                           });
                           this.getList();
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });          
                });
            },
            handleExport() {
                  const ids = this.$refs.tableRef.selection.map(item=>item.id)
                  const flag = ids.length === 0 ? '没有选择数据，默认导出模板':'确定将选择数据导出?'
                  this.$confirm(flag, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                   }).then(async() => {
                       const link = document.createElement('a');  // 创建元素
                       const result = await download(ids);
                        let blob = new Blob([result], { type: 'application/x-download' });
                        link.href = URL.createObjectURL(blob);   // 创建下载的链接
                        link.setAttribute('download', result.headers.filename );  // 给下载后的文件命名
                        document.body.appendChild(link);
                        link.click();  // 点击下载
                        document.body.removeChild(link);  //  下载完成移除元素
                        window.URL.revokeObjectURL(link.href);  // 释放掉blob对象
                    }).catch(() => {
                        this.$message({ 
                            type: 'info',
                            message: '已取消删除'
                        });          
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
.tips {
    color: #999;
    font-size: 12px;
    line-height: normal;
    margin-top: 8px;
    display: block; 
}
.pagination-container {
    padding: 10px;
    text-align: right;
}
</style>